<?php

class AFSQLImplementationException extends AFException {};
class AFSQLException extends AFException {};

class AFSQLModule extends AFModule
{
	protected $MySQL = 'MySQL';
	protected $PostgreSQL = 'PostgreSQL';
	protected $MicrosoftSQL = 'MicrosoftSQL';
	public $MYSQL = 'MySQL';
	public $PGSQL = 'PostgreSQL';
	public $MSSQL = 'MicrosoftSQL';

	private $connections = array();

	public function getClassName()
	{
		return 'AFSQL';
	}

	public function getModuleName()
	{
		return 'AFSQL';
	}

	public function __construct()
	{
		$this->dir = AF_MODULES_DIR . 'SQL' . AF_SEP;

		AFFunctions::walk($this->dir . AF_SEP . 'implementations', function($imp){
			include_once $imp;
		}, TRUE);
	}

//	public function newConnection($type)
//	{
//		return new $type;
//	}

	public function connect($name, $type /* , args... */)
	{
		$args = func_get_args();
		$args = array_slice($args, 2);
		$this->connections[$name] = new $type();
		call_user_func_array(array($this->connections[$name], 'connect'), $args);
//		$this->connections[$name] = call_user_func_array(array($type, '__construct'), $args); //new $type($args);
	}

	public function __get($name)
	{
//		call_user_func_array(array($this->connections[$name]), $arguments);
		if(!isset($this->connections[$name]))
		{
			throw new AFSQLImplementationException('Connection with handle `'.$name.'` not found.');
		}
		return $this->connections[$name];
	}

	public function __call($name, $arguments)
	{
		$conns = array_values($this->connections);
		$defaultConn = array_shift($conns);
		return call_user_func_array(array($defaultConn, $name), $arguments);
//		return $this->connections[$name];
	}
}

?>
